<template>
  <div class="container">
    <div class="page-header">
      <strong>数据点</strong>
    </div>
    <div class="filter-container">
      <!--<el-select v-model="q.type" class="filter-item" placeholder="请选择类型">
        <el-option
          v-for="item in dataEleTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>-->
      <div class="filter-item">
        <el-input v-model="q.id" placeholder="ID"/>
      </div>
      <div class="filter-item">
        <el-input v-model="q.code" placeholder="位号"/>
      </div>
      <div class="filter-item">
        <el-input v-model="q.itemCode" placeholder="指标编码"/>
      </div>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button
        v-permission="['Admin.Remote.Update']"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleUpdate()"
      >添加
      </el-button>
      <el-button
        v-permission="['Admin.Remote.Update']"
        :disabled="itemsChecked.length === 0"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="deleteData()"
      >批量删除
      </el-button>
      <el-upload v-permission="['Admin.Remote.Update']" action :show-file-list="false" :http-request="importDataEle"
                 class="filter-item">
        <el-button
          :loading="importLoading"
          type="primary"
          icon="el-icon-upload2"
        >导入数据点
        </el-button>
      </el-upload>
      <el-button
        v-permission="['Admin.Remote.Update']"
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="exportDataEle"
      >导出数据点
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="tableLoading"
      :data="dataElements"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="ID" prop="id" align="center" width="60"></el-table-column>
      <!--      <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>-->
      <!--      <el-table-column label="通道ID" prop="portId" align="center" width="90"></el-table-column>-->
      <el-table-column label="类型" align="center" min-width="90px">
        <template slot-scope="{row}">
          {{ transType(row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="位号" prop="code" min-width="90"></el-table-column>
      <el-table-column label="指标编码" prop="itemCode" align="center" min-width="100"></el-table-column>
      <el-table-column label="描述" prop="description" min-width="190"></el-table-column>
      <el-table-column label="单位" prop="unit" align="center" width="90"></el-table-column>
      <el-table-column label="功能码" align="center" min-width="90px">
        <template slot-scope="{row}">
          {{ row.modbusFuncCode?row.modbusFuncCode :"/" }}
        </template>
      </el-table-column>
      <el-table-column label="数据地址" align="center" min-width="90px">
        <template slot-scope="{row}">
          {{ row.modbusDataAddr || row.modbusDataAddr===0?row.modbusDataAddr :"/" }}
        </template>
      </el-table-column>
      <el-table-column label="偏移" align="center" min-width="70px">
        <template slot-scope="{row}">
          {{ row.modbusDataShift || row.modbusDataShift===0?row.modbusDataShift :"/" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-permission="['Admin.Remote.Update']" type="primary" size="mini" @click="handleUpdate(row)">编辑
          </el-button>
          <el-button v-permission="['Admin.Remote.Update']" size="mini" type="danger" @click="deleteData(row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page-index.sync="q.page"
      :page-size.sync="q.size"
      @pagination="getFullPageDataElement"
    />
    <edit-data-element-drawer
      ref="editDataElementDrawer"
      :equip-type="equipType"
      @save="getFullPageDataElement()"
    ></edit-data-element-drawer>
  </div>
</template>

<script>
  import { deleteDataElement, exportDataElement, importDataElement, getFullPageDataElement } from "@/api/dataElement";
  import { dataEleTypeOptions } from '@/utils/enums.js';
  import Pagination from "@/components/Pagination";
  import EditDataElementDrawer from "./EditDataElementDrawer";
  import _ from "lodash";

  export default {
    components: {
      'pagination': Pagination,
      'edit-data-element-drawer': EditDataElementDrawer
    },
    data() {
      return {
        dataEleTypeOptions,
        isSubmitLoading: false,
        downloadLoading: false,
        importLoading: false,
        tableLoading: false,
        tableKey: 0,
        equipType: undefined,
        itemsChecked: [],
        dataElements: [],
        q: {
          id: undefined,
          gatewayId: undefined,
          portId: undefined,
          equipId: undefined,
          itemCode: undefined,
          code: undefined,
          page: 1,
          size: 10,
          type: undefined
        },
        totalCount: 0
      };
    },
    computed: {},
    watch: {},
    created() {

    },
    methods: {
      handleSearch() {
        this.getFullPageDataElement();
      },
      getFullPageDataElement(gatewayId, portId, equipId, equipType) {
        if (portId && equipId) {
          this.q.gatewayId = gatewayId;
          this.q.portId = portId;
          this.q.equipId = equipId;
          this.q.type = undefined;
          this.equipType = equipType;
        }
        this.tableLoading = true;
        // 根据id查询某个通道信息
        getFullPageDataElement(this.q).then(result => {
          this.dataElements = result.content;
          this.totalCount = result.totalElements;
          this.tableLoading = false;
        });
      },
      selectionChange(selection) {
        this.itemsChecked = selection;
      },
      deleteData(id) {
        let selectedIds = [];
        if (id) {
          selectedIds = [{
            "gatewayId": this.q.gatewayId,
            "id": _.parseInt(id)
          }];
        } else {
          this.itemsChecked.map(item => {
            selectedIds.push({
              "gatewayId": item.gatewayId,
              "id": _.parseInt(item.id)
            })
          });
          if (selectedIds.length <= 0) {
            this.$message({ message: "至少选中一条记录", type: "warning" });
            return;
          }
        }

        this.$confirm("删除后不可恢复， 是否继续?", "确定执行删除操作吗？", {
          type: "warning"
        })
          .then(() => {
            deleteDataElement(selectedIds).then(() => {
              this.getFullPageDataElement();
              this.$message({ message: "删除成功", type: "success" });
            });
          })
          .catch(() => {
          });
      },
      transType(type) {
        let returnVal = '';
        switch (type) {
          case 1:
            returnVal = '模拟量';
            break;
          case 2:
            returnVal = '开关量';
            break;
          case 3:
            returnVal = '其他';
            break;
        }
        return returnVal;
      },
      handleUpdate(row) {
        this.$refs['editDataElementDrawer'].show(row, this.q);
      },
      importDataEle(fileObj) {
        this.$confirm("批量导入将清空并覆盖已配置数据点，确定继续吗？", "确定执行导入操作吗？", {
          type: "warning"
        })
          .then(() => {
            const loading = this.$loading({
              lock: true,
              text: '请稍候...',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.7)'
            });
            const param = new FormData();
            param.append("file", fileObj.file);
            importDataElement(this.q.gatewayId, this.q.portId, this.q.equipId, param).then(result => {
              loading.close();
              this.getFullPageDataElement();
              this.$message({
                message: "导入成功",
                type: "success"
              });
            });
          })
          .catch(() => {
          });
      },
      exportDataEle() {
        const loading = this.$loading({
          lock: true,
          text: '请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.7)'
        });
        exportDataElement(this.q.gatewayId, this.q.equipId).then(result => {
          this.download(result, '数据点配置.xlsx');
          loading.close();
        });
      },
      download(data, name) {
        const blob = new Blob([data]);
        const fileName = name;
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      },
      indexMethod(index) {
        return this.q.size * (this.q.page - 1) + index + 1;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .page-header {
    padding: 0;
    position: relative;
    margin: 0 0 15px;
    overflow: hidden;
    border-bottom: 2px solid #e4e7ed;

    strong {
      height: 38px;
      box-sizing: border-box;
      line-height: 38px;
      display: inline-block;
      list-style: none;
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      position: relative;
    }

  }

  .full-container {
    min-height: calc(100vh - 50px);
  }

  .import-data {
    display: inline-block;
  }
</style>
